﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ELMWCFServiceClass.ELMWCF;
using ELMApplication.Common.DataControl;
using System.Collections;
using ELMApplication.Common.Events;
using System.Reflection;

namespace ELMApplication.Common.UC
{
    public partial class ELMListUC : UserControl
    {
        ELMServiceClient _domainClient;
        public ELMListUC()
        {
            InitializeComponent();

        }
        public void ClearAllData()
        {
            datagrid.DataSource = dt=new DataTable("dt");
            btnAdd.Visibility = Visibility.Collapsed;
            datagrid.DataBind();
        }
        public void SetGridHeight(double height)
        {
            datagrid.Height = height;
        }
        DataTable dt = null;
        bool isCanAdd = true;
        public void LoadHuman(Guid contentTypeId)
        {
            dt = new DataTable("dt");
            dt.Columns.Add(new DataColumn("Key", "Key", false, false, false, true, false));
            dt.Columns.Add(new DataColumn("帐号", "帐号", true, true, true, false, true));
            dt.Columns.Add(new DataColumn("姓名", "姓名", true, true, true, false, true));
            dt.Columns.Add(new DataColumn("职位", "职位", true, true, true, false, true));
            _domainClient = new ELMServiceClient();
            _domainClient.GetContentTypeByIdAsync(contentTypeId);
            _domainClient.GetContentTypeByIdCompleted += (sender, data) =>
                {
                    if (data.Error == null)
                    {
                        foreach (var item in data.Result.Fields)
                        {
                            if (item.Key.IsDisplayInELMList)
                            {
                                dt.Columns.Add(new DataColumn(item.Key.FieldName, item.Key.FieldName, true, true, true, false, true));
                            }
                        }
                        _domainClient.GetAllHumanAsync();
                        _domainClient.GetAllHumanCompleted += (sender1, data1) =>
                        {
                            if (data1.Error == null)
                            {
                                foreach (var item in data1.Result)
                                {
                                    DataRow dr = new DataRow();
                                    dr["Key"] = item.HumanId;
                                    dr["帐号"] = item.HumanId;
                                    dr["姓名"] = item.HumanName;
                                    dr["职位"] = item.HumanDuty;
                                    foreach (var field in dt.Columns)
                                    {
                                        if (item.Attributes.Any(c => c.Key.FieldName == field.ColumnName))
                                        {
                                            dr[field.ColumnName] = item.Attributes.Single(c => c.Key.FieldName == field.ColumnName).Value;
                                        }
                                    }
                                    dt.Rows.Add(dr);
                                }
                                datagrid.DataSource = dt;

                                datagrid.DataBind();
                                DataLoaded();
                            }
                            else
                            {
                                throw data.Error;
                            }
                        };
                    }
                };
        }

        public void LoadMatter(Guid contentTypeId)
        {
            dt = new DataTable("dt");
            dt.Columns.Add(new DataColumn("Key", "Key", false, false, false, true, false));
            dt.Columns.Add(new DataColumn("物料编号", "物料编号", true, true, true, false, true));
            dt.Columns.Add(new DataColumn("物料名称", "物料名称", true, true, true, false, true));

            _domainClient = new ELMServiceClient();
            _domainClient.GetContentTypeByIdAsync(contentTypeId);
            _domainClient.GetContentTypeByIdCompleted += (sender, data) =>
            {
                if (data.Error == null)
                {
                    foreach (var item in data.Result.Fields)
                    {
                        if (item.Key.IsDisplayInELMList)
                        {
                            dt.Columns.Add(new DataColumn(item.Key.FieldName, item.Key.FieldName, true, true, true, false, true));
                        }
                    }
                    _domainClient.GetMattersAsync();
                    _domainClient.GetMattersCompleted += (sender1, data1) =>
                    {
                        if (data1.Error == null)
                        {
                            foreach (var item in data1.Result)
                            {
                                DataRow dr = new DataRow();
                                dr["Key"] = item.MatterId;
                                dr["物料编号"] = item.MatterId;
                                dr["物料名称"] = item.MatterName;

                                foreach (var field in dt.Columns)
                                {
                                    if (item.Attributes.Any(c => c.Key.FieldName == field.ColumnName))
                                    {
                                        dr[field.ColumnName] = item.Attributes.Single(c => c.Key.FieldName == field.ColumnName).Value;
                                    }
                                }
                                dt.Rows.Add(dr);
                            }
                            datagrid.DataSource = dt;

                            datagrid.DataBind();
                            DataLoaded();
                        }
                        else
                        {
                            throw data.Error;
                        }
                    };
                }
            };
        }
        public void SetControl(bool bl)
        {
            isCanAdd=bl;
            datagrid.Columns[0].Visibility = bl ? Visibility.Visible : Visibility.Collapsed;
           btnAdd.Visibility = bl ? Visibility.Visible : Visibility.Collapsed;
        }
        public void LoadCommonData(Guid contentTypeId, IEnumerable<ELMItem> datas)
        {
            dt = new DataTable("dt");
            dt.Columns.Add(new DataColumn("Key", "Key", false, false, false, true, false));


            _domainClient = new ELMServiceClient();
            _domainClient.GetContentTypeByIdAsync(contentTypeId);
            _domainClient.GetContentTypeByIdCompleted += (sender, data) =>
            {
                if (data.Error == null)
                {
                    foreach (var item in data.Result.Fields)
                    {
                        if (item.Key.IsDisplayInELMList)
                        {
                            dt.Columns.Add(new DataColumn(item.Key.FieldName, item.Key.FieldName, true, true, true, false, true));
                        }
                    }

                    foreach (var item in datas)
                    {
                        DataRow dr = new DataRow();
                        dr["Key"] = item.ELMItemId.ToString();

                        foreach (var field in dt.Columns)
                        {
                            if (item.Datas.Any(c => c.Key.FieldName == field.ColumnName))
                            {
                                dr[field.ColumnName] = item.Datas.Single(c => c.Key.FieldName == field.ColumnName).Value;
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                    datagrid.DataSource = dt;

                    datagrid.DataBind();
                    DataLoaded();
                   
                }
            };
            if (isCanAdd)
            {
                btnAdd.Visibility = Visibility.Visible;
            }
        
        }

        private void DataLoaded()
        {
            if (DataLoadCompleted != null)
            {
                DataLoadCompleted.Invoke(this, EventArgs.Empty);
            }
        }

        public event EventHandler<ELMListEventArgs> EditEvent;
        public event EventHandler<ELMListEventArgs> DelEvent;
        public event EventHandler<ELMListEventArgs> NewEvent;
        public event EventHandler DataLoadCompleted;
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            var data = datagrid.SelectedItem;
            if (DelEvent != null && data != null)
            {

                var arg = new ELMListEventArgs();
                object value = GetDataKeyValue(data);
                arg.DataKey = value.ToString();
                DelEvent.Invoke(sender, arg);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var data = datagrid.SelectedItem;
            if (EditEvent != null && data != null)
            {

                var arg = new ELMListEventArgs();
                object value = GetDataKeyValue(data);
                arg.DataKey = value.ToString();
                EditEvent.Invoke(sender, arg);
            }
        }
        private void NewClick(object sender, RoutedEventArgs e)
        {
            // var data = datagrid.SelectedItem;
            if (NewEvent != null)
            {

                var arg = new ELMListEventArgs();

                NewEvent.Invoke(sender, arg);
            }
        }

        private object GetDataKeyValue(object data)
        {
            Type myObject = data.GetType();
            PropertyInfo pi = myObject.GetProperty("KEY");
            object value = null;
            value = pi.GetValue(data, null);
            return value;
        }

        public void LoadDataDEMO()
        {
            // Create some sample names
            List<string> firstNames = new List<string>() { "Peter", "Frank", "Joe", "Lewis", "Jack", "Andrew", "Susan", "Marie", "Linda", "Anne", "Claire", "Debra" };
            List<string> lastNames = new List<string>() { "Smith", "Brown", "Green", "Parker", "Johnson", "Jackson", "Ford", "Sullivan" };

            // Create a sample DataTable
            DataTable dt = new DataTable("MyDataTable");

            // Create a column
            DataColumn dc1 = new DataColumn("col1");
            dc1.Caption = "First Name";
            dc1.ReadOnly = true;
            dc1.DataType = typeof(String);
            dc1.AllowResize = true;
            dc1.AllowSort = true;
            dc1.AllowReorder = true;
            dt.Columns.Add(dc1);

            // Create a column
            DataColumn dc2 = new DataColumn("col2");
            dc2.Caption = "Last Name";
            dc2.ReadOnly = true;
            dc2.DataType = typeof(String);
            dc2.AllowResize = true;
            dc2.AllowSort = true;
            dc2.AllowReorder = true;
            dt.Columns.Add(dc2);

            // Create a column
            DataColumn dc3 = new DataColumn("col3");
            dc3.Caption = "Age";
            dc3.ReadOnly = false;
            dc3.DataType = typeof(Int32);
            dt.Columns.Add(dc3);

            // Create a column
            DataColumn dc4 = new DataColumn("col4", "Married", true, true, true, true, true);
            dt.Columns.Add(dc4);

            // Create a column
            DataColumn dc5 = new DataColumn("col5", "Membership expiration", true, true, true, true, true);
            dt.Columns.Add(dc5);

            // Add sample rows to the table
            Random r = new Random();
            for (int i = 0; i < 15; i++)
            {
                DataRow dr = new DataRow();
                dr["col1"] = firstNames[r.Next(firstNames.Count)];
                dr["col2"] = lastNames[r.Next(lastNames.Count)];
                dr["col3"] = r.Next(20, 81);
                dr["col4"] = (r.Next(0, 2) == 1);
                dr["col5"] = DateTime.Now.AddDays(r.Next(10));
                dt.Rows.Add(dr);
            }

            // Create a DataSet and add the table to it
            DataSet ds = new DataSet("MyDataSet");
            ds.Tables.Add(dt);

            // Do the binding
            //datagrid.DataSource = ds;
            //datagrid.DataMember = "MyDataTable";
            //datagrid.DataBind();

            // We could do this as well
            // myBindableDG.DataSource = dt;
            // myBindableDG.DataBind();

        }


    }
}
